package com.sumainfor.pc.market.service.tenant.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.sumainfor.common.ConstantsHousing;
import com.sumainfor.common.NiuYunToken;
import com.sumainfor.common.exception.TCException;
import com.sumainfor.common.from.SearchHousingFrom;
import com.sumainfor.common.util.*;
import com.sumainfor.common.utlis.ComUtils;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.pc.market.dao.tenant.TcmktWorderEvaMapper;
import com.sumainfor.pc.market.dao.tenant.TeantHousingMapper;
import com.sumainfor.pc.market.feign.GetUserInfoFeign;
import com.sumainfor.pc.market.feign.Zfeign.ZpcEpcFeign;
import com.sumainfor.pc.market.feign.ZuulFeign.ZuulFeign;
import com.sumainfor.pc.market.service.tenant.TenantHousingService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.Period;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 房源操作服务实现类
 *
 * @Author Jack Chen
 * @Create 2019-01-29 14:33
 */
@Service
@Log4j2
@Transactional(rollbackFor = Exception.class)
public class TenantHousingServiceImpl implements TenantHousingService {

    @Autowired
    private TeantHousingMapper teantHousingMapper;

    @Autowired
    private ZpcEpcFeign feignEpc;

    @Autowired
    private ZuulFeign zuulFeign;

    @Autowired
    private GetUserInfoFeign userInfoFeign;

    @Autowired
    private ComUtils comUtils;

    //zc新加，判断租赁顾问是否评价
    @Autowired
    private TcmktWorderEvaMapper tcmktWorderEvaMapper;

    /**
     * 房源搜索 根据条件获取房源信息
     *
     * @param from
     * @param page
     * @return
     */
    @Override
    public JsonResult housingSelectList(SearchHousingFrom from, Page page) {
        Assert.notNull(from, "参数错误");

        if (CollectionUtils.isNotEmpty(from.getTrait())) {
            from.setTrait(teantHousingMapper.selectInIds(0, from.getTrait()));
        }

        if (CollectionUtils.isNotEmpty(from.getJoinValue()) && CollectionUtils.isNotEmpty(from.getWholeValue())) {
            from.setWhere("-1");
        } else if (CollectionUtils.isNotEmpty(from.getJoinValue())) {
            from.setWhere("0");
        } else if (CollectionUtils.isNotEmpty(from.getWholeValue())) {
            from.setWhere("1");
        } else {
            from.setWhere(null);
        }

        IPage<Map<String, Object>> data = teantHousingMapper.selectHousingListData(page, from);
        data.setRecords(data.getRecords().stream()
                .map(item -> {
                    if (MapUtils.getInteger(item, "Sublease", 0).equals(1)) {
                        item.put("HouInfoName", "转租·" + item.get("HouInfoName"));
                    }
                    if (StringUtils.isNotBlank(MapUtils.getString(item, "ShowImg"))) {
                        //处理图片
                        item.put("HouImg", item.get("ShowImg"));
                        item.remove("ShowImg");
                    } else {
                        item.put("HouImg", ConstantsHousing.DefaultHousingImg);
                    }


                    //处理楼层
                    item.put("floor", MapUtils.getString(item, "Floor") + "/" +
                            MapUtils.getString(item, "Floors") + "层");

                    //处理面积
                    if (MapUtils.getInteger(item, "IfOperaType").equals(1)) {
                        item.put("Area", item.get("Acreage") + "m²");
                    } else {
                        item.put("Area", item.get("Area") + "m²");
                    }

                    item.put("Acreage", item.get("Acreage") + "m²");

                    //处理查询房源特点
                    String inId = MapUtils.getString(item, "InId", "");
                    List<Object> trait = teantHousingMapper.selectDetailList(Lists.newArrayList(inId.split(",")))
                            .stream().map(tar -> tar.get("InName")).collect(Collectors.toList());

                    if (StringUtils.isNotBlank(MapUtils.getString(item, "Towards"))) {
                        trait.add("朝" + item.get("Towards"));
                    } else {
                        trait.add("朝" + MapUtils.getString(item, "Aspect"));
                        item.put("Towards", MapUtils.getString(item, "Aspect"));
                    }
                    item.remove("Aspect");
                    item.put("trait", trait);

                    item.remove("InId");

                    return item;
                }).collect(Collectors.toList()));
        return JsonResult.success(data);
    }


    /**
     * 根据编号查询房源的详细信息
     *
     * @param housingId
     * @return
     */
    @Override
    public JsonResult getHousingInfoById(String housingId) {
        List<Map<String, Object>> dataList = teantHousingMapper.getHousingInfoById(housingId);
        if (dataList.isEmpty()) {
            return JsonResult.error("没有查询到这个房源");
        }

        dataList = dataList.stream().map(item -> {
            if (MapUtils.getInteger(item, "Sublease", 0).equals(1)) {
                item.put("HouInfoName", "转租·" + item.get("HouInfoName"));
            }
            //处理楼层
            item.put("floor", MapUtils.getString(item, "Floor") + "/" +
                    MapUtils.getString(item, "Floors") + "层");
            item.remove("Floor");
            item.remove("Floors");

            //判断状态
            int state = MapUtils.getIntValue(item, "State");
            if (state == 0) {
                item.put("HousingState", "可预销");
            } else if (state == 1) {
                item.put("HousingState", "可入住");
            } else {
                if (MapUtils.getInteger(item, "Sublease", 0).equals(1)) {
                    item.put("HousingState", "已入住·转租");
                } else {
                    item.put("HousingState", "已入住");
                }
            }

            //处理图片,如果为空，就替换为默认图片
            if (!StringUtils.isNotBlank(MapUtils.getString(item, "HouseImg"))) {
                item.put("HouseImg", ConstantsHousing.DefaultHousingImg);
            }


            //处理面积
            if (StringUtils.isNotBlank(MapUtils.getString(item, "Area")) && MapUtils.getInteger(item, "IfOperaType").equals(0)) {
                item.put("Area", item.get("Area") + "m²");
            } else {
                item.put("Area", item.get("Acreage") + "m²");
            }

            //处理查询房源特点
            String inId = MapUtils.getString(item, "InId", "");
            List<Object> trait = teantHousingMapper.selectDetailList(Lists.newArrayList(inId.split(",")))
                    .stream().map(tar -> tar.get("InName")).collect(Collectors.toList());

            if (StringUtils.isBlank(MapUtils.getString(item, "Towards"))) {
                item.put("Towards", MapUtils.getString(item, "Aspect"));
            }

            item.put("trait", trait);
            item.remove("InId");
            ArrayList list = Lists.newArrayList();
            //图片处理
            if (!StringUtils.isNotBlank(MapUtils.getString(item, "DiningFile")) &&
                    !StringUtils.isNotBlank(MapUtils.getString(item, "KitchenFile"))) {
                list.add(ConstantsHousing.DefaultHousingImg);
            } else {
                list.addAll(Lists.newArrayList(MapUtils.getString(item, "DiningFile", "").split(",")));
                list.addAll(Lists.newArrayList(MapUtils.getString(item, "KitchenFile", "").split(",")));
            }
            item.put("PublicPicture", list);
            item.remove("DiningFile");
            item.remove("KitchenFile");
            //图片处理
            if (!StringUtils.isNotBlank(MapUtils.getString(item, "ToiletFile"))) {
                item.put("ToiletFile", Lists.newArrayList(ConstantsHousing.DefaultHousingImg));
            } else {
                item.put("ToiletFile", Lists.newArrayList(MapUtils.getString(item, "ToiletFile", "").split(",")));
            }

            item.put("TS", MapUtils.getIntValue(item, "ProLoculus", 0) + "室" + MapUtils.getIntValue(item, "ProHall", 0) + "厅");
            item.put("Towards", "朝" + (StringUtils.isNotBlank(MapUtils.getString(item, "Towards")) ? MapUtils.getString(item, "Towards") : MapUtils.getString(item, "Aspect")));
            item.remove("Aspect");
            return item;
        }).collect(Collectors.toList());

        if (dataList.size() == 1) {
            //单间房源
            Map<String, Object> map = dataList.get(0);
            //构建周边设施
            List<String> facilityIds = Lists.newArrayList(MapUtils.getString(map, "Facility", "").split(","));
            if (!facilityIds.isEmpty()) {
                map.put("facilityList", teantHousingMapper.selectFacilityByIds(facilityIds).stream().map(key -> {
                    key.put("FaUrl", NiuYunToken.publicQiniuUrl + MapUtils.getString(key, "FaUrl"));
                    return key;
                }).collect(Collectors.toList()));
            }

            //构建房源配置信息
            List<CustomMap> roomGroup = new ArrayList<>(2);
            //1.查询主表和详表数据
            JsonResult<List<Map<String, Object>>> configInfoJson = feignEpc.selectConfigInfoByConfigId(MapUtils.getString(map, "configID"));

            if (configInfoJson.isSuccess() && CollectionUtils.isNotEmpty(configInfoJson.getResult())) {
                List<Map<String, Object>> configs = configInfoJson.getResult();
                //查询房源基本信息主表数据信息
                Map<String, Object> configMainData = teantHousingMapper.getConfigMain(MapUtils.getString(map, "configID"));
                if (MapUtils.isEmpty(configMainData)) {
                    return JsonResult.error("查询主配置失败");
                }
                for (Map<String, Object> config : configs) {
                    config.putAll(configMainData);
                }
                //图片处理
                if (!StringUtils.isNotBlank(MapUtils.getString(configs.get(0), "HouInfoFile"))) {
                    //2.获得卧室图片
                    map.put("WsImageList", Lists.newArrayList(ConstantsHousing.DefaultHousingImg));
                } else {
                    //2.获得卧室图片
                    map.put("WsImageList", MapUtils.getString(configs.get(0), "HouInfoFile", "").split(","));
                }
                //3. 得到所有的商品编号集合
                List<String> shopIds = configs.stream().map(con -> MapUtils.getString(con, "ComId")).collect(Collectors.toList());
                //4. 调动远程EPC工程部服务获得商品的名称和Icon图标
                JsonResult<List<Map<String, Object>>> shopRes = feignEpc.getShopNameAndIconByIds(shopIds);
                if (shopRes.isSuccess()) {
                    List<Map<String, Object>> result = shopRes.getResult();
                    CustomMap roomItem = CustomMap.create("title", MapUtils.getString(configs.get(0), "HouConName"))
                            .put("count", result.size())
                            .put("data", result);
                    roomGroup.add(roomItem);
                } else {
                    log.error("出错信息 =====> {}", shopRes.toJson());
                    return JsonResult.error("房间配置信息找不到");
                }

                //5.查询公共区域设备
                List<Map<String, Object>> publicConfigByHousingId = teantHousingMapper.selectHousingPublicConfigByHousingId(MapUtils.getString(map, "HouId"));
                Set<String> hConIds = publicConfigByHousingId.stream().map(piv -> MapUtils.getString(piv, "HouCon")).collect(Collectors.toSet());
                if (hConIds.isEmpty()) {
                    return JsonResult.error("没有查询到公共区域数据异常");
                }
                //调用服务查询商品数据
                map.put("publicConfig", null);
                //获取工程部商品的编号
                JsonResult<List<String>> comIdArrayByConIdList = feignEpc.selectComIdArrayByConIdList(hConIds);

                if (!comIdArrayByConIdList.isSuccess()) {
                    throw new TCException("CODE:" + SystemUtils.getLineNumber() + " 获取公共区域设备失败");
                }

                List<String> publicShopIds = comIdArrayByConIdList.getResult();
                JsonResult<List<Map<String, Object>>> publicShopInfoRes = feignEpc.getShopNameAndIconByIds(publicShopIds);
                if (publicShopInfoRes.isSuccess()) {
                    List<Map<String, Object>> publicRes = publicShopInfoRes.getResult();
                    CustomMap roomItem = CustomMap.create("title", "公共区域")
                            .put("count", publicRes.size())
                            .put("data", publicRes);
                    map.put("publicConfig", roomItem);
                } else {
                    log.error("出错信息 =====> {}", shopRes.toJson());
                    return JsonResult.error("房间配置信息找不到");
                }

                //构建无线网络和电视是否开启了
                //1. 查询无线配置表
                //2. 查询是否开启了网络  初始化数据
                roomGroup.get(0).put("WifiPower", false).put("TvPower", false);
                for (Map<String, Object> powerItem : configs) {
                    if (MapUtils.getIntValue(powerItem, "SupType") == 3 && MapUtils.getIntValue(powerItem, "IfWiFi") == 0) {
                        roomGroup.get(0).put("WifiPower", true);
                    }
                    if (MapUtils.getIntValue(powerItem, "SupType") == 4 && MapUtils.getIntValue(powerItem, "IfWiFi") == 0) {
                        roomGroup.get(0).put("TvPower", true);
                    }
                }
            }


            //添加分组数据
            map.put("roomGroup", roomGroup);


            map.remove("Facility");
            map.remove("configID");

            //调用Zull 获得销售号码
            map.put("MarketMobileNumber", "");
            String peopleId = MapUtils.getString(map, "ShelfId");
            if (StringUtils.isNotBlank(peopleId)) {
                JsonResult<Map<String, Object>> result = zuulFeign.getMobileNumber(peopleId);
                if (result.isSuccess()) {
                    map.put("MarketMobileNumber", result.getResult().get("phone"));
                }
            }

            //查询这个房间的其他房源信息
            String mainId = MapUtils.getString(map, "HouId");
            List<Map<String, Object>> otherHousingInfo = teantHousingMapper.selectOtherHousingInfo(mainId);
            map.put("otherHousingList", otherHousingInfo.stream().map(other -> {
                Integer state = (Integer) other.get("State");
                //房源状态（0 待上架 1可签约 2已签约）
                switch (state) {
                    case 0:
                        other.put("StateText", "待上架");
                        break;
                    case 1:
                        other.put("StateText", "可入住");
                        break;
                    case 2:
                        other.put("StateText", "已入住");
                        break;
                }
                //判断是否是当前房源
                other.put("IsCurrent", false);
                if (MapUtils.getString(other, "HouInfoId").equals(housingId)) {
                    other.put("IsCurrent", true);
                }
                return other;
            }).collect(Collectors.toList()));


            //查询活动
            //1. 首先查询 价格
            Map<String, Object> firstData = teantHousingMapper.selectFirstData(housingId);
            List<String> activate = findOptimalActivate(housingId);
            if (MapUtils.isNotEmpty(firstData)) {
                if (activate.size() > 0) {
                    map.put("ActivateInfo", CustomMap.create("Price", firstData.get("Pricing"))
                            .put("ActivateList", activate));
                } else {
                    map.put("ActivateInfo", new HashMap<String, Object>());
                }
            } else {
                map.put("ActivateInfo", new HashMap<String, Object>());
            }


            return JsonResult.success(map);
        } else {
            //否则就是整租房源了 -----------------------------
            //基本数据
            Map<String, Object> map = dataList.get(0);
            //构建周边设施
            List<String> facilityIds = Lists.newArrayList(MapUtils.getString(map, "Facility", "").split(","));
            if (!facilityIds.isEmpty()) {
                map.put("facilityList", teantHousingMapper.selectFacilityByIds(facilityIds).stream().map(key -> {
                    key.put("FaUrl", NiuYunToken.publicQiniuUrl + MapUtils.getString(key, "FaUrl"));
                    return key;
                }).collect(Collectors.toList()));
            }

            //构建房源配置信息
            Set<String> wxPictureList = Sets.newHashSet();
            List<CustomMap> roomGroup = new ArrayList<>(2);
            //1.查询主表和详表数据
            for (Map<String, Object> item : dataList) {
                //1.查询主表和详表数据
                JsonResult<List<Map<String, Object>>> configInfoJson = feignEpc.selectConfigInfoByConfigId(MapUtils.getString(item, "configID"));


                if (configInfoJson.isSuccess() && CollectionUtils.isNotEmpty(configInfoJson.getResult())) {
                    List<Map<String, Object>> configs = configInfoJson.getResult();
                    //查询房源基本信息主表数据信息
                    Map<String, Object> configMainData = teantHousingMapper.getConfigMain(MapUtils.getString(map, "configID"));
                    if (MapUtils.isEmpty(configMainData)) {
                        return JsonResult.error("查询主配置失败");
                    }
                    for (Map<String, Object> config : configs) {
                        config.putAll(configMainData);
                    }


                    // 2.获得卧室图片
                    List<String> wxImgArray = teantHousingMapper.selectWsArrayByHouId((String) item.get("HouId"));
                    for (String wxImg : wxImgArray) {
                        wxPictureList.addAll(Lists.newArrayList(wxImg.split(",")));
                    }
                    //3. 得到所有的商品编号集合
                    List<String> shopIds = configs.stream().map(con -> MapUtils.getString(con, "ComId")).collect(Collectors.toList());
                    //4. 调动远程EPC工程部服务获得商品的名称和Icon图标
                    JsonResult<List<Map<String, Object>>> shopRes = feignEpc.getShopNameAndIconByIds(shopIds);
                    CustomMap roomItem = CustomMap.create();
                    if (shopRes.isSuccess()) {
                        List<Map<String, Object>> result = shopRes.getResult();
                        roomItem.put("title", MapUtils.getString(configs.get(0), "HouConName"))
                                .put("count", result.size())
                                .put("data", result);
                        roomGroup.add(roomItem);
                    } else {
                        log.error("出错信息 =====> {}", shopRes.toJson());
                        return JsonResult.error("房间配置信息找不到");
                    }

                    //构建无线网络和电视是否开启了
                    //1. 查询无线配置表
                    //2. 查询是否开启了网络  初始化数据
                    roomItem.put("WifiPower", false);
                    roomItem.put("TvPower", false);
                    for (Map<String, Object> powerItem : configs) {
                        if (MapUtils.getIntValue(powerItem, "SupType") == 3 && MapUtils.getIntValue(powerItem, "IfWiFi") == 0) {
                            roomGroup.get(0).put("WifiPower", true);
                        }
                        if (MapUtils.getIntValue(powerItem, "SupType") == 4 && MapUtils.getIntValue(powerItem, "IfWiFi") == 0) {
                            roomGroup.get(0).put("TvPower", true);
                        }
                    }

                }
                map.put("WsImageList", wxPictureList);


                //5.查询公共区域设备
                List<Map<String, Object>> publicConfigByHousingId = teantHousingMapper.selectHousingPublicConfigByHousingId(MapUtils.getString(map, "HouId"));
                Set<String> hConIds = publicConfigByHousingId.stream().map(piv -> MapUtils.getString(piv, "HouCon")).collect(Collectors.toSet());
                if (hConIds.isEmpty()) {
                    return JsonResult.error("没有查询到公共区域数据异常");
                }
                //调用服务查询商品数据
                map.put("publicConfig", null);

                //获取工程部商品的编号
                JsonResult<List<String>> comIdArrayByConIdList = feignEpc.selectComIdArrayByConIdList(hConIds);

                if (!comIdArrayByConIdList.isSuccess()) {
                    throw new TCException("CODE:" + SystemUtils.getLineNumber() + " 获取公共区域设备失败");
                }
                List<String> publicShopIds = comIdArrayByConIdList.getResult();
                JsonResult<List<Map<String, Object>>> publicShopInfoRes = feignEpc.getShopNameAndIconByIds(publicShopIds);
                if (publicShopInfoRes.isSuccess()) {
                    List<Map<String, Object>> publicRes = publicShopInfoRes.getResult();
                    CustomMap roomItem = CustomMap.create("title", "公共区域")
                            .put("count", publicRes.size())
                            .put("data", publicRes);
                    map.put("publicConfig", roomItem);
                } else {
                    return JsonResult.error("房间配置信息找不到");
                }
            }


            //添加分组数据
            map.put("roomGroup", roomGroup);

            map.remove("Facility");
            map.remove("configID");

            //调用Zull 获得销售号码
            map.put("MarketMobileNumber", "");
            String peopleId = MapUtils.getString(map, "ShelfId");
            if (StringUtils.isNotBlank(peopleId)) {
                JsonResult<Map<String, Object>> result = zuulFeign.getMobileNumber(peopleId);
                if (result.isSuccess()) {
                    map.put("MarketMobileNumber", result.getResult().get("phone"));
                }
            }

            //查询这个房间的其他房源信息
            String mainId = MapUtils.getString(map, "HouId");
            List<Map<String, Object>> otherHousingInfo = teantHousingMapper.selectOtherHousingInfo(mainId);
            map.put("otherHousingList", otherHousingInfo.stream().map(other -> {
                Integer state = (Integer) other.get("State");
                //房源状态（0 待上架 1可签约 2已签约）
                switch (state) {
                    case 0:
                        other.put("StateText", "待上架");
                        break;
                    case 1:
                        other.put("StateText", "可入住");
                        break;
                    case 2:
                        other.put("StateText", "已入住");
                        break;
                }
                //判断是否是当前房源
                other.put("IsCurrent", false);
                if (MapUtils.getString(other, "HouInfoId").equals(housingId)) {
                    other.put("IsCurrent", true);
                }
                return other;
            }).collect(Collectors.toList()));

            //查询活动
            //1. 首先查询 价格
            Map<String, Object> firstData = teantHousingMapper.selectFirstData(housingId);
            List<String> activate = findOptimalActivate(housingId);
//            map.put("ActivateInfo", CustomMap.create("Price", firstData.get("Pricing"))
//                    .put("ActivateList", activate));
            if (MapUtils.isNotEmpty(firstData)) {
                if (activate.size() > 0) {
                    map.put("ActivateInfo", CustomMap.create("Price", firstData.get("Pricing"))
                            .put("ActivateList", activate));
                } else {
                    map.put("ActivateInfo", new HashMap<String, Object>());
                }
            } else {
                map.put("ActivateInfo", new HashMap<String, Object>());
            }
            return JsonResult.success(map);
        }
    }


    /**
     * 发起预约房源
     *
     * @param params
     * @return
     */
    @Override
    public JsonResult makeHousing(Map<String, Object> params) {
        params.put("WoId", UUIDUtils.generatePrefixUuid("Word"));
        params.put("OperId", params.get("SetId"));
        //获取服务中心编号
        JsonResult<Integer> result = userInfoFeign.getCenterServiceInfo(MapUtils.getString(params, "SetId"));
        if (result.isSuccess()) {
            Integer deptId = result.getResult();
            params.put("SeId", deptId);
        }
        params.put("IfSeeing", 0);
        ParamsCommon.commonInsertParms(params);

        int row;

        //判断租客是否存在了
        int count = teantHousingMapper.checkTenantUserExist(MapUtils.getString(params, "TenId"));
        if (count == 0) {
            //不存在 就创建
            //创建职业信息数据
            String inmname = MapUtils.getString(params, "inmname");
            String jobId = null;
            if (!StringUtils.isBlank(inmname)) {
                Map<String, Object> map = teantHousingMapper.checkWordInfoIsExist(inmname);
                if (MapUtils.isEmpty(map)) {
                    //创建
                    jobId = UUIDUtils.generatePrefixUuid("Job");
                    row = teantHousingMapper.insertWordInfoData(ParamsCommon.commonInsertParms(CustomMap.create("JobId", jobId)
                            .put("JobName", inmname)
                            .put("delfg", 0)));
                    if (row <= 0) {
                        throw new TCException("创建职业数据失败");
                    }
                } else {
                    jobId = MapUtils.getString(map, "JobId");
                }
            }
            //todo 暂时给0
            params.put("IfLeaning", 0);
            params.put("TenStatus", 1);
            params.put("Status", 0);
            params.put("JobId", jobId);
            row = teantHousingMapper.insertTenantMainData(params);
            if (row <= 0) {
                throw new TCException("创建租客主表失败");
            }
        }

        //查询工单是否有这个租客的数据
        Map<String, Object> orderMain = teantHousingMapper.getWordOrderMainByTenId(MapUtils.getString(params, "TenId"));
        String woId = MapUtils.getString(orderMain, "WoId", null);
        if (MapUtils.isEmpty(orderMain)) {
            //为空说明是第一次
            //需要创建工单主表数据
            woId = comUtils.getLocalTrmSeqNumByLook("WO", "tcmkt", "tcmkt_worder", "WoId");
            Map<String, Object> inMap = ParamsCommon.commonInsertParms(CustomMap.create("WoId", woId)
                    .put("TenId", params.get("TenId"))
                    .put("SetId", params.get("SetId"))
                    .put("SeId", params.get("SeId"))
                    .put("Bind", new Date(System.currentTimeMillis()))
                    .put("delfg", 0));
            row = teantHousingMapper.insertWordOrderMain(inMap);
            if (row <= 0) {
                throw new TCException("创建工单主表失败");
            }
        } else {
            //读取时间判断是否到期了
            java.util.Date lastInfoDate = teantHousingMapper.getLastOrderInfoDataOne(woId, MapUtils.getString(params, "SetId"));
            if (lastInfoDate != null) {
                DateTime bindTime = new DateTime(MapUtils.getLongValue(orderMain, "Bind"));
                DateTime lastDateTime = new DateTime(lastInfoDate);
                Period period = new Period(bindTime, lastDateTime);
                int dayCount = period.getDays();
                //要几天差距解除客户和销售之家的绑定
                int differDay = 7;
                if (dayCount > differDay) {
                    //解除绑定
                    row = teantHousingMapper.updateWordOrderMainById(CustomMap.create("WoId", woId)
                            .put("Bind", new Date(System.currentTimeMillis()))
                            .put("SetId", params.get("SetId"))
                            .put("SeId", params.get("SeId"))
                            .put("updtm", new Date(System.currentTimeMillis()))
                    );
                    if (row <= 0) {
                        throw new TCException("重新绑定租客工单失败");
                    }
                }
            }
        }

        int notCount = teantHousingMapper.getNotDoneOrderCount(woId, MapUtils.getString(params, "HouInfoId"));
        if (notCount != 0) {
            throw new TCException("当前房源已经预约,请先完成之前的预约!");
        }

        //插入工单详表的数据
        CustomMap map = CustomMap.create()
                .put("WoInfoId", comUtils.getLocalTrmSeqNumByLook("WI", "tcmkt", "tcmkt_worder_info", "WoInfoId"))
                .put("WoId", woId)
                .put("OperId", params.get("SetId"))
                .put("MakeUserName", params.get("MakeUserName"))
                .put("IfSeeing", 0)
                .put("IfArrive", 0)
                .put("Remark", params.get("Remark"))
                .put("State", params.get("State"))
                .put("HouInfoId", params.get("HouInfoId"))
                .put("delfg", 0);
        if (StringUtils.isNotBlank(MapUtils.getString(params, "SeTime"))) {
            map.put("SeTime", DateTime.parse(MapUtils.getString(params, "SeTime"), DateTimeFormat.forPattern("yyyy-MM-dd HH:mm")).toDate());
        }
        row = teantHousingMapper.insertWordOrderInfoData(ParamsCommon.commonInsertParms(map));
        if (row <= 0) {
            throw new TCException("创建预约单失败");
        }
        return JsonResult.actionSuccess();
    }


    /**
     * 根据房源详表的编号查询 房源列表的数据
     *
     * @param page
     * @param ids
     * @return
     */
    @Override
    public JsonResult getHousingListByIds(Page page, List<String> ids) {
        IPage<Map<String, Object>> data = teantHousingMapper.selectHousingListByIds(page, ids);
        data.setRecords(data.getRecords().stream()
                .map(item -> {
                    //处理图片
                    item.put("HouImg", item.get("ShowImg"));
                    item.remove("ShowImg");
                    //处理楼层
                    item.put("floor", MapUtils.getString(item, "Floor") + "/" +
                            MapUtils.getString(item, "Floors") + "层");

                    //处理面积
                    item.put("Area", item.get("Area") + "m²");

                    //处理查询房源特点
                    String inId = MapUtils.getString(item, "InId", "");
                    List<Object> trait = teantHousingMapper.selectDetailList(Lists.newArrayList(inId.split(",")))
                            .stream().map(tar -> tar.get("InName")).collect(Collectors.toList());

                    if (StringUtils.isNotBlank(MapUtils.getString(item, "Towards"))) {
                        trait.add("朝" + item.get("Towards"));
                    } else {
                        trait.add("朝" + MapUtils.getString(item, "Aspect"));
                        item.put("Towards", MapUtils.getString(item, "Aspect"));
                    }
                    item.remove("Aspect");
                    item.put("trait", trait);

                    item.remove("InId");

                    return item;
                    //}).collect(Collectors.toList()));
                }).filter(
                        //item ->MapUtils.getInteger(item,"State")==0||MapUtils.getInteger(item,"State")==2
                        item -> MapUtils.getInteger(item, "State") == 1

                ).collect(Collectors.toList()));


        return JsonResult.success(data);
    }


    /**
     * 获得房源预约列表数据
     *
     * @param tenId
     * @return
     */
    @Override
    public JsonResult getMakeHousingList(String tenId) {
        List<Map<String, Object>> data = teantHousingMapper.selectMakeHousingList(tenId);
        data = data.stream().map(item -> {
            Timestamp createTime = (Timestamp) item.get("createTime");
            Date current = new Date();
            if (createTime!=null&&DateUtils.format(createTime, "yyyy-MM-dd").equals(DateUtils.format(current, "yyyy-MM-dd"))) {
                item.put("createTime", "今天 " + DateUtils.format(createTime, "HH:mm"));
            } else {
                item.put("createTime", DateUtils.format(createTime, "MM月dd日 HH:mm"));
            }

            //图片处理
            if (!StringUtils.isNotBlank(MapUtils.getString(item, "ShowImg"))) {
                item.put("ShowImg", ConstantsHousing.DefaultHousingImg);
            }

            item.put("Area", item.get("Area") + "㎡");
            item.put("Acreage", item.get("Acreage") + "㎡");
            item.put("ST", String.format("%s室%s厅", item.remove("ProLoculus"), item.remove("ProHall")));

            if (StringUtils.isBlank(MapUtils.getString(item, "Towards"))) {
                item.put("Towards", item.get("Aspect"));
            }
            item.remove("Aspect");

            item.put("Ce", String.format("%s/%s层", item.remove("Floor"), item.remove("Floors")));

            item.put("MarketMobileNumber", "");
            item.put("MarketUserName", "");
            String peopleId = MapUtils.getString(item, "OperId");

            item.put("SysUserId", MapUtils.getString(item, "OperId"));

            item.remove("OperId");
            if (StringUtils.isNotBlank(peopleId)) {
                JsonResult<Map<String, Object>> result = zuulFeign.getMobileNumber(peopleId);
                if (result.isSuccess()) {
                    item.put("MarketMobileNumber", result.getResult().get("phone"));
                    item.put("MarketUserName", result.getResult().get("userName"));
                }
            }
            return item;
        }).collect(Collectors.toList());

        //zc修改
        System.out.println("预约房源" + data);
        if (data.size() > 0) {
            for (Map<String, Object> zcMap : data) {
                System.out.println("每一次循环遍历的" + zcMap);
                if (!MapUtils.getString(zcMap, "WoInfoId").isEmpty()) {
                    //zc修改,添加租赁顾问是否评价，zccount如果大于0，那么就表示评价过了
                    Map<String, Object> worderEvaMap = new HashMap<>();
                    worderEvaMap.put("TenId", tenId);
                    worderEvaMap.put("WoInfoId", MapUtils.getString(zcMap, "WoInfoId"));
                    System.out.println("判断租赁顾问评价" + worderEvaMap);
                    zcMap.put("zccount", tcmktWorderEvaMapper.getWorderEvaCount(worderEvaMap));
                }
            }
        }

        return JsonResult.success(data);
    }


    /**
     * 查询最优活动
     *
     * @param infoId
     * @return
     */
    private List<String> findOptimalActivate(String infoId) {
        List<String> text = Lists.newArrayList();
        //先查询主表数据1
        Map<String, Object> data = teantHousingMapper.selectFirstData(infoId);
        if (MapUtils.isNotEmpty(data)) {
            Integer type = MapUtils.getInteger(data, "ActType");
            String assId = MapUtils.getString(data, "AssId");
            //活动类型   1.满减类  2.付款方式  3满送类   4首月类
            switch (type) {
                case 1:
                    text.add(getAcvitateMj(assId));
                    break;
                case 2:
                    text.addAll(getActivatePay(assId));
                    break;
                case 3:
                    text.addAll(getActivateMs(assId));
                    break;
                case 4:
                    text.addAll(getActivateSy(assId));
                    break;
            }
        }
        return text;
    }

    /**
     * 查询满减
     *
     * @param id
     * @return
     */
    private String getAcvitateMj(String id) {
        Map<String, Object> data = teantHousingMapper.getActivateMj(id);
        int time = MapUtils.getIntValue(data, "FulDuration");
        StringBuffer sb = new StringBuffer();
        sb.append("签约满").append(time).append("月");
        if (data.get("FulMoney") == null) {
            sb.append("打").append(data.get("FulOff")).append("折");
        } else {
            sb.append("减").append(data.get("FulMoney")).append("元");
        }
        return sb.toString();
    }


    private List<String> getActivatePay(String id) {
        StringBuffer sb = new StringBuffer();
        List<String> list = new ArrayList<>();
        Map<String, Object> data = teantHousingMapper.getActivatePay(id);
        //付款类型  1月付  2季付  3半年付  4年付
        switch (MapUtils.getInteger(data, "PayType")) {
            case 1:
                sb.append("月付");
                break;
            case 2:
                sb.append("季付");
                break;
            case 3:
                sb.append("半年付");
                break;
            case 4:
                sb.append("年付");
                break;
        }
        if (data.get("FulMoney") == null) {
            sb.append("打").append(data.get("FulOff")).append("折");
        } else {
            sb.append("减").append(data.get("FulMoney")).append("元");
        }
        list.add(sb.toString());

        Integer type = MapUtils.getInteger(data, "SouType");
        String souId = MapUtils.getString(data, "SouId");
        //来源类型  1.满减类  2.付款方式  3满送类   4首月类
        if (type != null) {
            switch (type) {
                case 1:
                    list.add(getAcvitateMj(souId));
                    break;
                case 2:
                    list.addAll(getActivatePay(souId));
                    break;
                case 3:
                    list.addAll(getActivateMs(souId));
                    break;
                case 4:
                    list.addAll(getActivateSy(souId));
                    break;
            }
        }
        return list;
    }


    private List<String> getActivateMs(String id) {
        StringBuffer sb = new StringBuffer();
        List<String> list = new ArrayList<>();
        Map<String, Object> data = teantHousingMapper.getActivateMs(id);
        sb.append("签满");
        sb.append(data.get("Duration")).append("月").append("送").append(data.get("SenSend")).append("月");
        list.add(sb.toString());

        Integer type = MapUtils.getInteger(data, "SouType");
        String souId = MapUtils.getString(data, "SouId");
        //来源类型  1.满减类  2.付款方式  3满送类   4首月类
        if (type != null) {
            switch (type) {
                case 1:
                    list.add(getAcvitateMj(souId));
                    break;
                case 2:
                    list.addAll(getActivatePay(souId));
                    break;
                case 3:
                    list.addAll(getActivateMs(souId));
                    break;
                case 4:
                    list.addAll(getActivateSy(souId));
                    break;
            }
        }
        return list;
    }

    private List<String> getActivateSy(String id) {
        StringBuffer sb = new StringBuffer();
        List<String> list = new ArrayList<>();
        Map<String, Object> data = teantHousingMapper.getActivateSy(id);
        sb.append("首月签满").append(data.get("FirDuration")).append("月");
        if (data.get("FulMoney") == null) {
            sb.append("打").append(data.get("FulOff")).append("折");
        } else {
            sb.append("减").append(data.get("FulMoney")).append("元");
        }
        list.add(sb.toString());

        Integer type = MapUtils.getInteger(data, "SouType");
        String souId = MapUtils.getString(data, "SouId");
        //来源类型  1.满减类  2.付款方式  3满送类   4首月类
        if (type != null) {
            switch (type) {
                case 1:
                    list.add(getAcvitateMj(souId));
                    break;
                case 2:
                    list.addAll(getActivatePay(souId));
                    break;
                case 3:
                    list.addAll(getActivateMs(souId));
                    break;
                case 4:
                    list.addAll(getActivateSy(souId));
                    break;
            }
        }
        return list;
    }


    /**
     * 评价一个预约单
     *
     * @param params
     * @return
     */
    @Override

    public JsonResult commentMakeOrder(Map<String, Object> params) {
        String infoId = MapUtils.getString(params, "WoInfoId");
        Integer evaGrade = MapUtils.getInteger(params, "EvaGrade");
        String evalabel = MapUtils.getString(params, "Evalabel");
        String evaContent = MapUtils.getString(params, "EvaContent");

        if (StringUtils.isBlank(infoId)
                || evaGrade == null
                || StringUtils.isBlank(evalabel)
                || StringUtils.isBlank(evaContent)) {
            return JsonResult.errorForEmpty();
        }

        if (evaGrade < 0 || evaGrade > 5) {
            return JsonResult.error("评价星只能在 0-5 区间");
        }

        int update = teantHousingMapper.commentMakeOrder(ParamsCommon.commonUpdateParms(params));
        return update <= 0 ? JsonResult.error("评价失败") : JsonResult.success("评价成功");
    }


}